package com.cars.nfp.service;

import com.cars.nfp.expired.AuthExpired;
import com.cars.util.json.JsonResult;
import com.cars.util.json.JsonResultUtil;
import com.cars.util.jwt.JwtResult;
import com.cars.util.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cars.nfp.token.Token;

import java.util.HashMap;
import java.util.Map;

/**
 * 操作 TOKEN
 * <p>
 * 生成token、刷新tokne
 *
 * @author 宋长军
 * @date 2019/8/15 17:23
 */
@Service
public class TokenService {

    @Autowired
    private AuthRedisService authRedisService;

    /**
     * 根据用户名、密码、系统标识获取token信息
     *
     * @return token信息
     */
    public Token getTokenByPass(String username) {

        // 创建并存储新的token
        String accessToken = JwtUtil.generateJWT(AuthExpired.TOKEN_EXPIRED, username, 1, 1);
        String refreshToken = JwtUtil.generateJWT(AuthExpired.REFRESH_TOKEN_EXPIRED, username, 1, 1);

        return new Token(accessToken, refreshToken);
    }

    /**
     * 根据refresh_token刷新access_token
     *
     * @param refreshToken refresh_token
     * @return 新的token
     */
    public JsonResult getTokenByRefresh(String refreshToken) {
        JsonResult jsonResult;
        JwtResult jwtResult = JwtUtil.parseJWT(refreshToken);
        boolean isValid = jwtResult.isValid();

        // 校验refreshtoken是否有效
        if (isValid) {
            String username = jwtResult.getOwner();
            String token = JwtUtil.generateJWT(AuthExpired.TOKEN_EXPIRED, username, 1,1);

            Map<String, String> map = new HashMap<>(2);
            map.put("accessToken", token);
            map.put("refreshToken", refreshToken);
            jsonResult = JsonResultUtil.ok(map);
            authRedisService.saveUserAccessToken(username, JwtUtil.parseJWT(token).getToken());
        } else {
            jsonResult = JsonResultUtil.error("无效的REFRESH_TOKEN!");
        }
        return jsonResult;
    }
}
